﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace AddBorders
{
    static class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(@"D:\Temp\Photos");
            const int desiredWidth = 800;
            const int desiredHeight = 600;
            Color borderColor = Color.Black;

            FileInfo[] fileInfos = directoryInfo.GetFiles("*.jpg");
            foreach (var fileInfo in fileInfos)
            {
                using (Image sourceImage = Image.FromFile(fileInfo.FullName))
                {
                    if (sourceImage.Width == desiredWidth && sourceImage.Height == desiredHeight)
                        continue;

                    Console.WriteLine(fileInfo.FullName);
                    using (Image destinationImage = new Bitmap(desiredWidth, desiredHeight, sourceImage.PixelFormat))
                    {
                        using (Graphics g = Graphics.FromImage(destinationImage))
                        {
                            Brush borderBrush = new SolidBrush(borderColor);
                            g.FillRectangle(borderBrush, 0, 0, desiredWidth, desiredHeight);
                            int offsetX = (desiredWidth - sourceImage.Width)/2;
                            Rectangle destinationRect = new Rectangle(offsetX, 0, sourceImage.Width, sourceImage.Height);
                            Rectangle sourceRect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
                            g.DrawImage(sourceImage, destinationRect, sourceRect, GraphicsUnit.Pixel);
                        }

                        ImageFormat sourceImageFormat = sourceImage.RawFormat;
                        sourceImage.Dispose();
                        destinationImage.Save(fileInfo.FullName, sourceImageFormat);
                    }
                }
            }
        }
    }
}
